package com.itheima.springboottlias.aspect;


import Pojo.Emp;
import Pojo.EmpLoginLog;
import Pojo.LogInfor;
import Pojo.Result;
import com.itheima.springboottlias.mapper.LoginOperateLogMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@Component
@Aspect
public class EmpOperationLoginLog {
    @Autowired
    private LoginOperateLogMapper  loginOperateLogMapper;
    
    @Around("execution(* com.itheima.springboottlias.controller.LoginController.login(..))")
    public Object recordLoginLog(ProceedingJoinPoint pjp) throws Throwable {
        //记录操作日志:收集操作日志信息,添加到操作日志表中
        long start = System.currentTimeMillis();
        Object result = null;
        try {
            result = pjp.proceed();
        } catch (Throwable e) {
            result = Result.error(e.getMessage());
        } finally {
            long end = System.currentTimeMillis();
            long costTime = end - start;


            Result result1 = (Result) result;
            LogInfor data = (LogInfor) result1.getData();
            String token = null;
            if (data != null) {
                token = (String) data.getToken();
            }
            int code = result1.getCode();
            short isSuccess = (short) code;
            Emp emp= (Emp) pjp.getArgs()[0];
            EmpLoginLog empLoginLog = new EmpLoginLog();
            empLoginLog.setUsername(emp.getUsername());
            empLoginLog.setPassword(emp.getPassword());
            empLoginLog.setLoginTime(LocalDateTime.now());
            empLoginLog.setIsSuccess(isSuccess);
            empLoginLog.setJwt(token);
            empLoginLog.setCostTime(costTime);

            loginOperateLogMapper.insert(empLoginLog);

        }
        return result;
    }
}
